package com.ltmall.api.filter;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.io.PrintWriter;

public class LoggerFilter implements Filter {

	private Logger logger = LogManager.getLogger(LoggerFilter.class);

	public static void main(String[] args) {

	}

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
//		BufferedReader reader = request.getReader();
		String output = "";
//		try {
//			String str = "";
//			String line = "";
//			while ((line = reader.readLine()) != null) {
//				line = URLDecoder.decode(line, "utf-8");
//				System.out.println(line);
//				str += line;
//			}
//			output = "线程：" + String.valueOf(Thread.currentThread().getId()) + "-请求主体：" + str;
//			System.out.println("doFilter request: " + output);
//			logger.info(output);
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//			if (reader != null) {
//				reader.close();
//			}
//		}

		response.setCharacterEncoding("utf-8");
		final CopyPrintWriter writer = new CopyPrintWriter(response.getWriter());
		chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {
			@Override
			public PrintWriter getWriter() {
				return writer;
			}
		});

		output = "线程：" + String.valueOf(Thread.currentThread().getId()) + "-响应主体" + writer.getCopy();
		System.out.println("doFilter resopnse: " + output);
		logger.info(output);
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
